﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HQPad.Models;
using HQPad.DAL;
using HQPad.Services;
using HQPad.Helpers;

namespace HQPad.Controllers
{
    public class ReleaseController : BaseController
    {
        // Get list of releases.
        public ActionResult Index()
        {
            BuildPageTitle("Release note management");

            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);

            // Get all postings for 'release' group.
            IEnumerable<Posting> releases = service.GetPostings("Release").OrderBy(p => p.PostingKey);

            return View(releases);
        }

        public ActionResult Delete(int id)
        {
            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);

            service.DeletePosting(id);
            membershipContext.Save();

            return RedirectToAction("index");
        }

        /// <summary>
        /// Create a new release and go straight over to the edit view.
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            BuildPageTitle("Create a new release note.");

            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);
            string userName = AuthenticationHelper.GetCurrentUserName(HttpContext);
            
            // create new posting.
            Posting posting = new Posting()
            {
                Content = string.Empty,
                Created = DateTime.Now,
                LastModified = DateTime.Now,
                PostingGroup = "Release",
                UserName = userName
            };

            return View(posting);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Posting posting, FormCollection formCollection)
        {
            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);

            // catch existing release key error.
            Posting existing = service.GetPostingByKey("Release", posting.PostingKey);

            if (existing != null)
            {
                ModelState.AddModelError("Release", string.Format("Unable to save changes. The generated release key {0} already exists in the system, try a different key.", posting.PostingKey));
            }

            if (ModelState.IsValid)
            {
                try
                {

                    service.Add(posting);

                    membershipContext.Save();
                    return RedirectToAction("index");
                }
                catch (DataException)
                {
                    //Log the error (add a variable name after DataException)
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }

            BuildPageTitle("Create a new release note.");
            return View(posting);
        }

        /// <summary>
        /// Load the editor view.
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);

            Posting posting = service.GetPostingById(id);

            BuildPageTitle(string.Format("Edit release note {0}.", posting.PostingKey));
            
            return View(posting);
        }

        /// <summary>
        /// Load the editor view and handle post back.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Posting posting, FormCollection form)
        {
            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);
            string userName = AuthenticationHelper.GetCurrentUserName(HttpContext);


            BuildPageTitle(string.Format("Edit release note {0}.", posting.PostingKey));

            if (ModelState.IsValid)
            {
                try
                {
                    service.SavePosting(posting, userName);

                    membershipContext.Save();
                    return RedirectToAction("index");
                }
                catch (DataException)
                {
                    //Log the error (add a variable name after DataException)
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }

            return View(posting);
        }

        public ActionResult History()
        {
            IUnitOfWork membershipContext = new MembershipContext();
            IPostingService service = new PostingService((MembershipContext)membershipContext);

            var postings = service.GetPostings("Release").OrderByDescending(r => r.PostingKey).ToList();

            return View(postings);
        }
    }
}